package cn.com.ejiakanghu.service;

import cn.com.ejiakanghu.core.config.DirectExchangeRabbitMQConfig;
import cn.com.ejiakanghu.core.exception.CheckException;
import cn.com.ejiakanghu.core.exceptions.BizException;
import cn.com.ejiakanghu.core.rabbitmq.DirectExchangeProducer;
import cn.com.ejiakanghu.core.utils.RespUtil;
import cn.com.ejiakanghu.core.vo.BaseResult;
import cn.com.ejiakanghu.dto.*;
import cn.com.ejiakanghu.form.*;
import cn.com.ejiakanghu.vo.ScanGunBindInfoLockerVo;
import cn.com.ejiakanghu.vo.ScanGunBindInfoVo;
import cn.ejiakanghu.logistics.service.impl.LogisticBusiBaseServiceImpl;
import cn.ejiakanghu.logistics.service.impl.OrderStateService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.linlinjava.litemall.db.config.ServerAddress;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.logistics.LogisticsMapper;
import org.linlinjava.litemall.db.dao.order_manage.AgedmallLocksMapper;
import org.linlinjava.litemall.db.dao.order_manage.AgedmallShopMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.jsonfield.LitemallGoodsProductSpecification;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.service.rfid.AgedmallLgRfidStateService;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.db.vo.app.InStockStoreGoodsDto;
import org.linlinjava.litemall.db.vo.app.InStockStoreOrderDto;
import org.linlinjava.litemall.db.vo.app.RfidGoodsVo;
import org.linlinjava.litemall.db.vo.locks.PickUp;
import org.linlinjava.litemall.db.vo.logistics.LogisticsCommonData;
import org.linlinjava.litemall.db.vo.logistics.LogisticsGoodsData;
import org.linlinjava.litemall.db.vo.shop.ChainLockPickup;
import org.linlinjava.litemall.db.vo.shop.MedicalLockPickup;
import org.linlinjava.litemall.db.vo.shop.StoreCloudPickup;
import org.linlinjava.litemall.db.vo.store.StoreGoodsBack;
import org.linlinjava.litemall.db.vo.wechat.ToLitemallBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class ScanGunManager {
    @Autowired
    private AgedmallStoreService agedmallStoreService;
    @Autowired
    private AgedmallRfidGoodsProductService agedmallRfidGoodsProductService;
    @Autowired
    private LitemallGoodsProductService litemallGoodsProductService;
    @Autowired
    private LitemallGoodsSpecificationService litemallGoodsSpecificationService;
    @Autowired
    private AgedmallGoodsSpecificationInfoService agedmallGoodsSpecificationInfoService;
    @Autowired
    private AgedmallCabinetGoodsService agedmallCabinetGoodsService;
    @Resource
    private AgedmallScanGunsMapper agedmallScanGunsMapper;
    @Resource
    private AgedmallCabinetMapper agedmallCabinetMapper;
    @Resource
    private AgedmallCabinetGoodsMapper agedmallCabinetGoodsMapper;
    @Resource
    private LitemallAftersaleMapper litemallAftersaleMapper;
    @Resource
    private AgedmallShopMapper agedmallShopMapper;
    @Resource
    private AgedmallLgBaseInfoMapper agedmallLgBaseInfoMapper;
    @Resource
    private OrderStateService orderStateService;
    @Resource
    private AgedmallLgRfidStateService agedmallLgRfidStateService;
    @Resource
    private AgedmallRfidGoodsProductMapper agedmallRfidGoodsProductMapper;
    @Resource
    private AgedmallLgRfidGoodsCurStatMapper agedmallLgRfidGoodsCurStatMapper;
    @Resource
    private LogisticsMapper logisticsMapper;
    @Resource
    private LogisticBusiBaseServiceImpl logisticBusiBaseServiceImpl;
    @Resource
    private AgedmallLgMissionMapper agedmallLgMissionMapper;
    @Resource
    private AgedmallStoreMapper agedmallStoreMapper;
    @Resource
    private GoodsManager goodsManager;
    @Resource
    private AgedmallStoreGoodsMapper agedmallStoreGoodsMapper;
    @Resource
    private LitemallGoodsProductMapper litemallGoodsProductMapper;
    @Resource
    private AgedmallLocksMapper agedmallLocksMapper;
    @Resource
    private AgedmallStoreGoodsService agedmallStoreGoodsService;
    @Resource
    private LitemallGoodsSpecificationService goodsSpecificationService;
    @Resource
    private DirectExchangeProducer directExchangeProducer;
    @Resource
    private LitemallOrderGoodsMapper litemallOrderGoodsMapper;
    @Resource
    private ServerAddress serverAddress;


    /**
     * rfid 衣柜锁相关修改
     */
    public void changeRfidGoodsState(String rfid,Integer rfidGoodsProductState,Integer cabinetGoodsState){
        AgedmallRfidGoodsProductExample goodsProductExample=new AgedmallRfidGoodsProductExample();
        goodsProductExample.or().andRfidEqualTo(rfid).andDeletedEqualTo(false);
        AgedmallRfidGoodsProduct goodsProduct=agedmallRfidGoodsProductMapper.selectOneByExample(goodsProductExample);
        goodsProduct.setStat(rfidGoodsProductState);
        agedmallRfidGoodsProductMapper.updateByPrimaryKey(goodsProduct);
        AgedmallCabinetGoodsExample cabinetGoodsExample=new AgedmallCabinetGoodsExample();
        cabinetGoodsExample.or().andGoodsRfidIdEqualTo(goodsProduct.getId()).andDeletedEqualTo(false);
        AgedmallCabinetGoods cabinetGoods=agedmallCabinetGoodsMapper.selectOneByExample(cabinetGoodsExample);
        cabinetGoods.setStat(cabinetGoodsState);
        agedmallCabinetGoodsMapper.updateByPrimaryKey(cabinetGoods);
    }

    /**
     * rfid 衣柜锁相关修改-批量
     */
    public void changeRfidGoodsStateBatch(List<String> rfid,Integer rfidGoodsProductState,Integer cabinetGoodsState,Integer curStat){
        AgedmallRfidGoodsProductExample goodsProductExample=new AgedmallRfidGoodsProductExample();
        goodsProductExample.or().andRfidIn(rfid).andDeletedEqualTo(false);
        List<AgedmallRfidGoodsProduct> goodsProduct=agedmallRfidGoodsProductMapper.selectByExample(goodsProductExample);
        AgedmallRfidGoodsProduct rfidGoodsProduct=new AgedmallRfidGoodsProduct();
        rfidGoodsProduct.setStat(rfidGoodsProductState);
        agedmallRfidGoodsProductMapper.updateByExampleSelective(rfidGoodsProduct,goodsProductExample);
        List<Long> goodsProductList=new ArrayList<>();
        goodsProduct.forEach(goods ->goodsProductList.add(goods.getId()));
        AgedmallCabinetGoodsExample cabinetGoodsExample=new AgedmallCabinetGoodsExample();
        cabinetGoodsExample.or().andGoodsRfidIdIn(goodsProductList).andDeletedEqualTo(false);
        AgedmallCabinetGoods cabinetGoods=agedmallCabinetGoodsMapper.selectOneByExample(cabinetGoodsExample);
        cabinetGoods.setStat(cabinetGoodsState);
        agedmallCabinetGoodsMapper.updateByExampleSelective(cabinetGoods,cabinetGoodsExample);
        AgedmallLgRfidGoodsCurStatExample rfidGoodsCurStatExample=new AgedmallLgRfidGoodsCurStatExample();
        rfidGoodsCurStatExample.or().andRfidIn(rfid).andTypeEqualTo(2);
        AgedmallLgRfidGoodsCurStat goodsCurStat=new AgedmallLgRfidGoodsCurStat();
        goodsCurStat.setCurStat(curStat);
        agedmallLgRfidGoodsCurStatMapper.updateByExampleSelective(goodsCurStat,rfidGoodsCurStatExample);
    }

    /**
     *  根据rfid获取当前missionId
     */
    public Integer getMission(String rfid,Integer type){
        return logisticsMapper.selectCabinetMissionByRfid(rfid,type);
    }


    /**
     * 数据库状态-->前端状态
     */
    public Integer dbStateToWebState(Integer state){
        switch (state){
            case 0:
            case 5:
                return 1;
            case 2:
                return 2;
            case 3:
            case 4:
            case 6:
            case 1:
            default:
                return 0;
        }
    }

    /**
     * 前端状态--> 数据库状态
     */
    public Integer webStateToDbState(Integer state){
        switch (state){
            case 0:
                return 1;
            case 2:
                return 2;
            case 1:
                return 0;
            default:
                return 6;
        }
    }



    public BaseResult bindStore(String deviceId, String storeId) {
        AgedmallStore store = agedmallStoreService.findStoreById(Long.parseLong(storeId));
        if (null == store) {
            return RespUtil.badArgumentValue();
        }
        // 已绑定 先解绑
        AgedmallScanGunsExample agedmallScanGunsExample = new AgedmallScanGunsExample();
        agedmallScanGunsExample.createCriteria().andDeletedEqualTo((byte)0)
                .andRfidEqualTo(deviceId);
        agedmallScanGunsMapper.logicalDeleteByExample(agedmallScanGunsExample);

        AgedmallScanGuns scanGuns = new AgedmallScanGuns();
        scanGuns.setRfid(deviceId);
        scanGuns.setStoreId(Long.parseLong(storeId));
        scanGuns.setDeleted((byte)0);
        scanGuns.setAddTime(LocalDateTime.now());
        scanGuns.setStat(0);
        scanGuns.setOnlineTime(LocalDateTime.now());
        agedmallScanGunsMapper.insertSelective(scanGuns);

        ScanGunBindInfoLockerVo lockerVo = null;
        AgedmallCabinetExample agedmallCabinetExample = new AgedmallCabinetExample();
        agedmallCabinetExample.createCriteria().andDeletedEqualTo((byte)0)
                .andStoreIdEqualTo(Long.parseLong(storeId));
        AgedmallCabinet agedmallCabinet = agedmallCabinetMapper.selectOneByExample(agedmallCabinetExample);
        if (null != agedmallCabinet) {
            lockerVo = new ScanGunBindInfoLockerVo(agedmallCabinet.getRfid());
        }
        ScanGunBindInfoVo scanGunBindInfoVo = ScanGunBindInfoVo.getInstance(store, lockerVo);
        return RespUtil.success(scanGunBindInfoVo);
    }

    public BaseResult unBindStore(String deviceId) {
        AgedmallScanGunsExample agedmallScanGunsExample = new AgedmallScanGunsExample();
        agedmallScanGunsExample.createCriteria().andDeletedEqualTo((byte)0)
                .andRfidEqualTo(deviceId);
        agedmallScanGunsMapper.logicalDeleteByExample(agedmallScanGunsExample);
        return RespUtil.success();
    }

    public BaseResult bindLocker(String storeId, String lockerId) {
        AgedmallStore store = agedmallStoreService.findStoreById(Long.parseLong(storeId));
        if (null == store) {
            return RespUtil.badArgumentValue();
        }
        AgedmallCabinetExample agedmallCabinetExample = new AgedmallCabinetExample();
        agedmallCabinetExample.createCriteria().andDeletedEqualTo((byte)0)
                .andStoreIdEqualTo(Long.parseLong(storeId));
        AgedmallCabinet agedmallCabinet = agedmallCabinetMapper.selectOneByExample(agedmallCabinetExample);
        if (null != agedmallCabinet) {
            throw new BizException("门店已绑定医柜");
        }
        // 已绑定 先解绑
        AgedmallCabinetExample cabinetExample = new AgedmallCabinetExample();
        cabinetExample.createCriteria().andDeletedEqualTo((byte)0)
                .andRfidEqualTo(lockerId);
        agedmallCabinetMapper.logicalDeleteByExample(cabinetExample);

        AgedmallCabinet cabinet = new AgedmallCabinet();
        cabinet.setStoreId(Long.parseLong(storeId));
        cabinet.setPosition("门店");
        cabinet.setRfid(lockerId);
        cabinet.setDeleted((byte)0);
        cabinet.setAddTime(LocalDateTime.now());
        cabinet.setStat(0);
        cabinet.setOnlineTime(LocalDateTime.now());
        agedmallCabinetMapper.insertSelective(cabinet);

        ScanGunBindInfoLockerVo lockerVo = new ScanGunBindInfoLockerVo();
        lockerVo.setId(lockerId);
        return RespUtil.success(lockerVo);
    }

    public BaseResult unBindLocker(String lockerId) {
        AgedmallCabinetExample cabinetExample = new AgedmallCabinetExample();
        cabinetExample.createCriteria().andDeletedEqualTo((byte)0)
                .andRfidEqualTo(lockerId);
        agedmallCabinetMapper.logicalDeleteByExample(cabinetExample);
        return RespUtil.success();
    }

    public BaseResult bindInfo(String deviceId) {
        AgedmallScanGunsExample agedmallScanGunsExample = new AgedmallScanGunsExample();
        agedmallScanGunsExample.createCriteria().andDeletedEqualTo((byte)0)
                .andRfidEqualTo(deviceId);
        AgedmallScanGuns agedmallScanGuns = agedmallScanGunsMapper.selectOneByExample(agedmallScanGunsExample);
        if (null == agedmallScanGuns) {
            return RespUtil.success();
        }
        AgedmallStore store = agedmallStoreService.findStoreById(agedmallScanGuns.getStoreId());
        ScanGunBindInfoLockerVo lockerVo = null;
        AgedmallCabinetExample agedmallCabinetExample = new AgedmallCabinetExample();
        agedmallCabinetExample.createCriteria().andDeletedEqualTo((byte)0)
                .andStoreIdEqualTo(agedmallScanGuns.getStoreId());
        AgedmallCabinet agedmallCabinet = agedmallCabinetMapper.selectOneByExample(agedmallCabinetExample);
        if (null != agedmallCabinet) {
            lockerVo = new ScanGunBindInfoLockerVo(agedmallCabinet.getRfid());
        }
        ScanGunBindInfoVo scanGunBindInfoVo = ScanGunBindInfoVo.getInstance(store, lockerVo);
        return RespUtil.success(scanGunBindInfoVo);
    }

    public BaseResult storeGoodsByRfidList(StoreGoodsByRfidListForm storeGoodsByRfidListForm) {
        List<String> rfidList = Arrays.asList(storeGoodsByRfidListForm.getRfidList());
        List<RfidGoodsVo> rfidGoodsVos = agedmallRfidGoodsProductService.storeGoodsByRfidList(rfidList);
        for (RfidGoodsVo rfidGoodsVo : rfidGoodsVos) {
            String specName = "";
            LitemallGoodsProduct goodsProduct = litemallGoodsProductService.findById(rfidGoodsVo.getSkuId());
            if (null != goodsProduct) {
                List<LitemallGoodsProductSpecification> specifications = JSON.parseArray(goodsProduct.getSpecifications(), LitemallGoodsProductSpecification.class);
                if (CollectionUtils.isNotEmpty(specifications)) {
                    for (LitemallGoodsProductSpecification specification : specifications) {
                        LitemallGoodsSpecification goodsSpecification = litemallGoodsSpecificationService.findById(specification.getId());
                        if (null != goodsSpecification.getParentId()) {
                            AgedmallGoodsSpecificationInfo specificationInfo = agedmallGoodsSpecificationInfoService.getById(goodsSpecification.getParentId());
                            if (null != specificationInfo) {
                                specName += ";" + specificationInfo.getSpecName() + ":" + specification.getName();
                            }
                        }
                    }
                }
            }
            rfidGoodsVo.setSkuName(specName.replaceFirst(";", ""));
        }
        for (int i = 0; i < rfidGoodsVos.size(); i++) {
            rfidGoodsVos.get(i).setStatus(dbStateToWebState(rfidGoodsVos.get(i).getStatus()));
        }
        return RespUtil.success(rfidGoodsVos);
    }

    @Transactional
    public BaseResult updateStoreGoods(ScanGunUpdateStoreGoodsListForm listForm) {
        if (CollectionUtils.isNotEmpty(listForm.getGoodsList())) {
            for (ScanGunUpdateStoreGoodsForm scanGunUpdateStoreGoodsForm : listForm.getGoodsList()) {
                AgedmallRfidGoodsProduct rfidGoodsProduct = agedmallRfidGoodsProductService.findByRfid(scanGunUpdateStoreGoodsForm.getRfid());
                if (null != rfidGoodsProduct) {
                    agedmallCabinetGoodsService.updateStatByRfid(rfidGoodsProduct.getId(), webStateToDbState(scanGunUpdateStoreGoodsForm.getStatus()));
                }
            }
        }
        return RespUtil.success();
    }

    public BaseResult editStoreGoodsStatus(String deviceId, String rfid, Integer status) {
        AgedmallScanGunsExample agedmallScanGunsExample = new AgedmallScanGunsExample();
        agedmallScanGunsExample.createCriteria().andDeletedEqualTo((byte)0)
                .andRfidEqualTo(deviceId);
        AgedmallScanGuns agedmallScanGuns = agedmallScanGunsMapper.selectOneByExample(agedmallScanGunsExample);
        if (null == agedmallScanGuns) {
            return RespUtil.badArgumentValue();
        }
        AgedmallRfidGoodsProduct rfidGoodsProduct = agedmallRfidGoodsProductService.findByRfidAndStoreId(rfid, agedmallScanGuns.getStoreId().intValue());
        if (null != rfidGoodsProduct) {
            rfidGoodsProduct.setStat(webStateToDbState(status));
            rfidGoodsProduct.setMaintainReason("");
            agedmallRfidGoodsProductMapper.updateByPrimaryKey(rfidGoodsProduct);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("updateTime", DateUtil.formatLocalDateTime(LocalDateTime.now()));
        return RespUtil.success(map);
    }

    public BaseResult searchStoreGoods(String rfid) {
        RfidGoodsVo rfidGoodsVo = agedmallRfidGoodsProductService.storeGoodsByRfid(rfid);
        if(ObjectUtil.isNull(rfidGoodsVo)){
            return RespUtil.fail(1505,"rfid不存在");
        }
        String specName = "";
        LitemallGoodsProduct goodsProduct = litemallGoodsProductService.findById(rfidGoodsVo.getSkuId());
        if (null != goodsProduct) {
            List<LitemallGoodsProductSpecification> specifications = JSON.parseArray(goodsProduct.getSpecifications(), LitemallGoodsProductSpecification.class);
            if (CollectionUtils.isNotEmpty(specifications)) {
                for (LitemallGoodsProductSpecification specification : specifications) {
                    LitemallGoodsSpecification goodsSpecification = litemallGoodsSpecificationService.findById(specification.getId());
                    if (null != goodsSpecification.getParentId()) {
                        AgedmallGoodsSpecificationInfo specificationInfo = agedmallGoodsSpecificationInfoService.getById(goodsSpecification.getParentId());
                        if (null != specificationInfo) {
                            specName += ";" + specificationInfo.getSpecName() + ":" + specification.getName();
                        }
                    }
                }
            }
        }
        rfidGoodsVo.setSkuName(specName.replaceFirst(";", ""));
        rfidGoodsVo.setStatus(dbStateToWebState(rfidGoodsVo.getStatus()));
        return RespUtil.success(rfidGoodsVo);
    }

    public BaseResult storeGoods(String deviceId) {
        AgedmallScanGunsExample agedmallScanGunsExample = new AgedmallScanGunsExample();
        agedmallScanGunsExample.createCriteria().andDeletedEqualTo((byte)0)
                .andRfidEqualTo(deviceId);
        AgedmallScanGuns agedmallScanGuns = agedmallScanGunsMapper.selectOneByExample(agedmallScanGunsExample);
        if (null == agedmallScanGuns) {
            return RespUtil.badArgumentValue();
        }

        List<RfidGoodsVo> rfidGoodsVos = agedmallRfidGoodsProductService.storeGoodsByStoreId(agedmallScanGuns.getStoreId()+"");
        for (RfidGoodsVo rfidGoodsVo : rfidGoodsVos) {
            String specName = "";
            LitemallGoodsProduct goodsProduct = litemallGoodsProductService.findById(rfidGoodsVo.getSkuId());
            if (null != goodsProduct) {
                List<LitemallGoodsProductSpecification> specifications = JSON.parseArray(goodsProduct.getSpecifications(), LitemallGoodsProductSpecification.class);
                if (CollectionUtils.isNotEmpty(specifications)) {
                    for (LitemallGoodsProductSpecification specification : specifications) {
                        LitemallGoodsSpecification goodsSpecification = litemallGoodsSpecificationService.findById(specification.getId());
                        if (null != goodsSpecification.getParentId()) {
                            AgedmallGoodsSpecificationInfo specificationInfo = agedmallGoodsSpecificationInfoService.getById(goodsSpecification.getParentId());
                            if (null != specificationInfo) {
                                specName += ";" + specificationInfo.getSpecName() + ":" + specification.getName();
                            }
                        }
                    }
                }
            }
            rfidGoodsVo.setSkuName(specName.replaceFirst(";", ""));
        }
        for (int i = 0; i < rfidGoodsVos.size(); i++) {
            rfidGoodsVos.get(i).setStatus(dbStateToWebState(rfidGoodsVos.get(i).getStatus()));
        }
        return RespUtil.success(rfidGoodsVos);
    }

    public BaseResult editStoreGoodsRfid(String deviceId, String oldRfid, String newRfid) {
        AgedmallScanGunsExample agedmallScanGunsExample = new AgedmallScanGunsExample();
        agedmallScanGunsExample.or().andDeletedEqualTo((byte)0)
                .andRfidEqualTo(deviceId);
        AgedmallScanGuns agedmallScanGuns = agedmallScanGunsMapper.selectOneByExample(agedmallScanGunsExample);
        if (null == agedmallScanGuns) {
            return RespUtil.badArgumentValue();
        }
        agedmallRfidGoodsProductService.updateRfid(agedmallScanGuns.getStoreId()+"", oldRfid, newRfid);
        Map<String,Object> map=new HashMap<>();
        map.put("updateTime", DateUtil.formatLocalDateTime(LocalDateTime.now()));
        return RespUtil.success(map);
    }

    /**
     * 获取两个集合中不重复的id 即衣柜锁中不存在的
     */
    public static List<Long> getUnRepetition(List<Long> list1,
                                              List<Long> list2) {
        List<Long> result = new ArrayList<>();
        for (Long integer : list2) {
            if (!list1.contains(integer)) {
                result.add(integer);
            }
        }
        return result;
    }

    public BaseResult getResultMessage(String result){
        JSONObject jsonObject = JSON.parseObject(result);
        Object data =jsonObject.get("data") ;
        String msg =(String)jsonObject.get("errmsg") ;
        int code =(int)jsonObject.get("errno") ;
        if(code!=0){
            return RespUtil.fail(code,msg);
        }
        else if(ObjectUtil.isNotNull(data)){
            return RespUtil.success(data);
        }
        else {
            return RespUtil.success();
        }
    }

    public int ResultIsError(String result){
        JSONObject jsonObject = JSON.parseObject(result);
        Object data =jsonObject.get("data") ;
        String msg =(String)jsonObject.get("errmsg") ;
        return (int)jsonObject.get("errno");
    }


    public List<InStockStoreGoodsDto> checkSameRfid(List<InStockStoreGoodsDto> inStockStoreGoodsDtos,String rfid,Integer stockType){
        for (int i = 0; i < inStockStoreGoodsDtos.size(); i++) {
            if(inStockStoreGoodsDtos.get(i).getRfid().equals(rfid)){
                inStockStoreGoodsDtos.get(i).setInStockType(stockType);
            }
        }
        return inStockStoreGoodsDtos;
    }

    public BaseResult inStockStoreGoods(InStockStoreGoodsForm inStockStoreGoodsForm,String deviceId){
        //获取所有rfid信息
        List<InStockStoreGoodsDto> inStockStoreGoodsDtos = agedmallRfidGoodsProductService.
                selectGoodsMessageByInStockStoreGoods(inStockStoreGoodsForm.getRfidList());
        if(inStockStoreGoodsDtos.isEmpty()){
            return RespUtil.fail(3001,"请先录入商品rfid");
        }
        //获取衣柜锁id
        AgedmallScanGunsExample agedmallScanGunsExample = new AgedmallScanGunsExample();
        agedmallScanGunsExample.or().andDeletedEqualTo((byte)0)
                .andRfidEqualTo(deviceId);
        AgedmallScanGuns agedmallScanGuns = agedmallScanGunsMapper.selectOneByExample(agedmallScanGunsExample);
        AgedmallCabinetExample cabinetExample=new AgedmallCabinetExample();
        cabinetExample.or().andDeletedEqualTo((byte)0).andStoreIdEqualTo(agedmallScanGuns.getStoreId());
        AgedmallCabinet cabinet = agedmallCabinetMapper.selectOneByExample(cabinetExample);
        Long cabinetId = cabinet.getId();

        List<Long> goodsRfidIds=new ArrayList<>();
        inStockStoreGoodsDtos.forEach(inStockStoreGoodsDto -> goodsRfidIds.add(inStockStoreGoodsDto.getGoodProductId()));
        //获取已经被衣柜锁绑定的商品
        AgedmallCabinetGoodsExample cabinetGoodsExample=new AgedmallCabinetGoodsExample();
        cabinetGoodsExample.or().andGoodsRfidIdIn(goodsRfidIds).andDeletedEqualTo(false);
        List<AgedmallCabinetGoods> agedmallCabinetGoods = agedmallCabinetGoodsMapper.selectByExample(cabinetGoodsExample);
        List<Long> cabinetGoodsRfidIds=new ArrayList<>();
        agedmallCabinetGoods.forEach(cabinetGoods -> cabinetGoodsRfidIds.add(cabinetGoods.getGoodsRfidId()));
        //需要新增的id
        List<Long> needInsertIds=getUnRepetition(cabinetGoodsRfidIds,goodsRfidIds);

        //新增操作
        List<AgedmallCabinetGoods> insertCabinetGoodsList=new ArrayList<>();
        for (int i = 0; i < needInsertIds.size(); i++) {
            AgedmallCabinetGoods cabinetGoods=new AgedmallCabinetGoods();

            for (int j = 0; j < inStockStoreGoodsDtos.size(); j++) {
                if(inStockStoreGoodsDtos.get(j).getGoodProductId().equals(needInsertIds.get(i))){
                    //绑定医柜
                    cabinetGoods.setCabinetId(cabinetId);
                    cabinetGoods.setAddTime(LocalDateTime.now());
                    cabinetGoods.setStat(0);
                    cabinetGoods.setGoodsRfidId(needInsertIds.get(i));
                    //设置为新增
                    inStockStoreGoodsDtos.get(j).setInStockType(0);
                }
            }
            insertCabinetGoodsList.add(cabinetGoods);
        }
        if(!insertCabinetGoodsList.isEmpty()){
            agedmallRfidGoodsProductService.insertCabinetGoodsBatch(insertCabinetGoodsList);
        }
        //接下来操作中去掉新增
        goodsRfidIds.removeAll(needInsertIds);
        if(goodsRfidIds.isEmpty()){
            return RespUtil.success(inStockStoreGoodsDtos);
        }
        //判断rfid状态
        List<String> curRfidList=new ArrayList<>();
        goodsRfidIds.forEach( goodsRfid ->curRfidList.add(goodsRfid.toString()) );
        AgedmallLgRfidGoodsCurStatExample curStatExample=new AgedmallLgRfidGoodsCurStatExample();
        curStatExample.or().andTypeEqualTo(2).andRfidIn(curRfidList);
        List<AgedmallLgRfidGoodsCurStat> agedmallLgRfidGoodsCurStatList = agedmallLgRfidGoodsCurStatMapper.selectByExample(curStatExample);


        for (int i = 0; i < agedmallLgRfidGoodsCurStatList.size(); i++) {
            //归还
            if(agedmallLgRfidGoodsCurStatList.get(i).getCurStat()==2){
                //返回当前状态
                inStockStoreGoodsDtos=checkSameRfid(inStockStoreGoodsDtos,agedmallLgRfidGoodsCurStatList.get(i).getRfid(),1);
                //修改相关表状态
                changeRfidGoodsState(agedmallLgRfidGoodsCurStatList.get(i).getRfid(),2,6);
                agedmallLgRfidStateService.changeLgRfidState(agedmallLgRfidGoodsCurStatList.get(i).getRfid(),11,2);
            }
            //TODO 剩下的售后   拒收  换货拒收 退换货
        }

        return RespUtil.success(inStockStoreGoodsDtos);
    }


    public BaseResult orderPickupList(OrderPickupListForm orderPickupListForm){
        OrderPickUpListInfo orderPickUpListInfo=new OrderPickUpListInfo();
        String[] split = orderPickupListForm.getPrinterCode().split("-");
        if(split.length<2){
            return RespUtil.fail(1501,"打印订单号错误");
        }
        AgedmallLgMission mission = agedmallLgMissionMapper.selectByPrimaryKey(Integer.parseInt(split[1]));
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(mission.getBaseInfoId().longValue());

        if(!agedmallLgBaseInfo.getLgStat().equals(LgBaseInfoStatConstant.BUY_ALLOTING)&&
                !agedmallLgBaseInfo.getLgStat().equals(LgBaseInfoStatConstant.CHANGE_SENDING)&&
                !agedmallLgBaseInfo.getLgStat().equals(LgBaseInfoStatConstant.PICK_UP_ALLOTING)){
            return RespUtil.fail(1502,"不在配货状态");
        }
        if(ObjectUtil.isNull(agedmallLgBaseInfo)){
            return RespUtil.fail(1500,"打印订单不存在");
        }
        List<Integer> idList=new ArrayList<>();
        LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(agedmallLgBaseInfo.getLgContent());

        List<LogisticsGoodsData> goodsDataList = commonData.getGoodsDataList();
        goodsDataList.forEach( goodsData-> idList.add(goodsData.getOrderGoodsId()));


        //门店
        List<StoreCloudPickup> storePickups = agedmallShopMapper.selectStoreGoodsMessage(idList);
        //云仓
        List<StoreCloudPickup> cloudPickups = agedmallShopMapper.selectCloudGoodsMessage(idList);

        List<StoreCloudPickup> backStoreCloudList = new ArrayList<>();
        if(!storePickups.isEmpty()){
            storePickups.forEach( storePickup ->{
                storePickup.setStockType(0);
                backStoreCloudList.add(storePickup);
            });

        }
        if(!cloudPickups.isEmpty()){
            cloudPickups.forEach( cloudPickup ->{
                cloudPickup.setStockType(1);
                backStoreCloudList.add(cloudPickup);
            });
        }
        //链条锁
        LitemallOrderGoodsExample chainOrderGoodsExample=new LitemallOrderGoodsExample();
        chainOrderGoodsExample.or().andIdIn(idList).andStockTypeEqualTo(1);
        List<LitemallOrderGoods> chainOrderGoods=litemallOrderGoodsMapper.selectByExample(chainOrderGoodsExample);
        //衣柜锁
        LitemallOrderGoodsExample medicalOrderGoodsExample=new LitemallOrderGoodsExample();
        medicalOrderGoodsExample.or().andIdIn(idList).andStockTypeEqualTo(2);
        List<LitemallOrderGoods> medicalOrderGoods=litemallOrderGoodsMapper.selectByExample(medicalOrderGoodsExample);

        //衣柜锁和软链数量处理
        List<MedicalLockPickup> backMediccalLock=new ArrayList<>();
        if(!medicalOrderGoods.isEmpty()){
            medicalOrderGoods.forEach( medical ->{
                String[] rfidList = medical.getRfid().split(",");
                List<String> rfidsList = Arrays.asList(rfidList);
                List<MedicalLockPickup> medicalLockPickups = agedmallShopMapper.selectMedicalLockGoodsMessage(rfidsList);
                backMediccalLock.addAll(medicalLockPickups);
                for (int i = 0; i < backMediccalLock.size(); i++) {
                    backMediccalLock.get(i).setPid(i+1);
                }
                });
        }
        List<ChainLockPickup> backChainLock=new ArrayList<>();
        if(!chainOrderGoods.isEmpty()){
            chainOrderGoods.forEach( chain ->{
                String[] rfidList = chain.getRfid().split(",");
                List<Integer> rfidsList = new ArrayList<>();
                for (int i = 0; i <rfidList.length ; i++) {
                    rfidsList.add(Integer.parseInt(rfidList[i]));
                }
                List<ChainLockPickup> chainLockPickup = agedmallShopMapper.selectEquGoodsMessage(rfidsList);
                backChainLock.addAll(chainLockPickup);
                for (int i = 0; i < backChainLock.size(); i++) {
                    backChainLock.get(i).setPid(i+1);
                }
            });
        }
        orderPickUpListInfo.setChainLockPickupList(backChainLock);
        orderPickUpListInfo.setMedicalLockPickupList(backMediccalLock);
        orderPickUpListInfo.setStoreCloudPickupList(backStoreCloudList);
        AgedmallStore storeById = agedmallStoreService.findStoreById(agedmallLgBaseInfo.getStoreId());
        if(storeById.getDeliveryMode()==3){
            orderPickUpListInfo.setIsSubmitExpressCode(1);
        }
        else{
            orderPickUpListInfo.setIsSubmitExpressCode(0);
        }

        return RespUtil.success(orderPickUpListInfo);
    }

    public BaseResult finishOrderPickup(FinishOrderPickupForm finishOrderPickupForm) throws CheckException {
        List<PickUp> rfidList=finishOrderPickupForm.getPickupList();
        String[] split = finishOrderPickupForm.getPrinterCode().split("-");
        if(split.length<2){
            return RespUtil.fail(1501,"打印订单号错误");
        }
        List<ChainLockPickup> chainLockPickups = logisticBusiBaseServiceImpl.deployOverEvent(Integer.parseInt(split[1]),
                finishOrderPickupForm.getBase64Images(), rfidList,finishOrderPickupForm.getExpressCode(),null,false);
        Map<String,Object> map=new HashMap<>();
        boolean isFinish=true;
        if(chainLockPickups!=null&&!chainLockPickups.isEmpty()){
            for (ChainLockPickup chain:chainLockPickups) {
                if(chain.getPickUpStatus()==0){
                    isFinish=false;
                }
            }
            map.put("chainLockPickupList",chainLockPickups);
        }
            map.put("isPickupFinish",isFinish?1:0);
        return RespUtil.success(map);
    }

    public BaseResult finishOfflinePickup(FinishOfflinePickupForm finishOfflinePickupForm){
        List<String> rfidList=new ArrayList<>();
        finishOfflinePickupForm.getPickupList().forEach( pickUp -> rfidList.add(pickUp.getRfid()));
        changeRfidGoodsStateBatch(rfidList,6,4,12);
        return RespUtil.success();
    }

    public BaseResult getStoreGoodsList(StoreGoodsListForm form){
        List<StoreGoodsDto> storeGoodsDtos=new ArrayList<>();
        AgedmallScanGunsExample agedmallScanGunsExample = new AgedmallScanGunsExample();
        agedmallScanGunsExample.or().andDeletedEqualTo((byte)0)
                .andRfidEqualTo(form.getDeviceId());
        AgedmallScanGuns agedmallScanGuns = agedmallScanGunsMapper.selectOneByExample(agedmallScanGunsExample);
        if (null == agedmallScanGuns) {
            return RespUtil.badArgumentValue();
        }
        Page page=PageHelper.startPage(form.getPage(), form.getLimit());
        List<StoreGoodsBack> storeGoodsIdList = logisticsMapper.getStoreGoodsIdList(agedmallScanGuns.getStoreId().intValue(), form.getKeywords());
        storeGoodsIdList.forEach( storeGoods ->{
            List<AgedmallGoodsSpecificationInfo> goodsSpecificationInfoList = agedmallGoodsSpecificationInfoService.getByGoodsIdAndType(storeGoods.getGoodsId(), AgedmallGoodsSpecificationInfoConstant.TYPE_SPEC);
            List<Sku> skuList = goodsSpecificationInfoList.stream()
                    .map(p -> {
                        List<LitemallGoodsSpecification> goodsSpecificationList = goodsSpecificationService.queryByParentId(p.getId());
                        List<GoodsSpecItemInfo> itemInfoList = goodsSpecificationList.stream().map(GoodsSpecItemInfo::getInstance).collect(Collectors.toList());
                        GoodsSpecDataInfo goodsSpecDataInfo = new GoodsSpecDataInfo();
                        Sku sku=new Sku();
                        goodsSpecDataInfo.setId(p.getId());
                        sku.setSkuId(p.getId());
                        sku.setName(p.getSpecName());
                        List<Spec> specs=new ArrayList<>();
                        itemInfoList.forEach( itemInfo ->{
                            Spec spec=new Spec();
                            spec.setName(itemInfo.getName());
                            spec.setId(itemInfo.getId());
                            specs.add(spec);
                        });
                        sku.setSpecList(specs);
                        return sku;
                    }).collect(Collectors.toList());
            StoreGoodsDto storeGoodsDto=new StoreGoodsDto();
            storeGoodsDto.setSkuList(JSONArray.parseArray(JSON.toJSONString(skuList)));
            storeGoodsDto.setGoodsId(storeGoods.getGoodsId());
            storeGoodsDto.setType(storeGoods.getType());
            storeGoodsDto.setGoodsName(storeGoods.getName());
            storeGoodsDto.setGoodsImg(storeGoods.getGoodsImg());
            storeGoodsDtos.add(storeGoodsDto);
        });
        Map<String,Object> map=new HashMap<>();
        map.put("totalRows",page.getTotal());
        map.put("totalPage",page.getPages());
        map.put("nowPage",form.getPage());
        map.put("rows",storeGoodsDtos);
        return RespUtil.success(map);
    }

    public BaseResult storeAddGoods(StoreAddGoodsForm storeAddGoodsForm){
        AgedmallScanGunsExample agedmallScanGunsExample = new AgedmallScanGunsExample();
        agedmallScanGunsExample.or().andDeletedEqualTo((byte)0)
                .andRfidEqualTo(storeAddGoodsForm.getDeviceId());
        AgedmallScanGuns agedmallScanGuns = agedmallScanGunsMapper.selectOneByExample(agedmallScanGunsExample);
        if (null == agedmallScanGuns) {
            return RespUtil.badArgumentValue();
        }
        //获取规格信息
        List<LitemallGoodsProductSpecification> skuFormatDtos=new ArrayList<>();
        for (int i = 0; i < storeAddGoodsForm.getSkuInfo().size(); i++) {
            SkuInfoVo skuInfoVo = storeAddGoodsForm.getSkuInfo().get(i);
            LitemallGoodsProductSpecification formatDto=new LitemallGoodsProductSpecification();
            formatDto.setId(skuInfoVo.getSpecId());
            formatDto.setName(skuInfoVo.getSpecName());
            formatDto.setInfoId(skuInfoVo.getSkuId());
            formatDto.setInfoName(skuInfoVo.getSkuName());
            skuFormatDtos.add(formatDto);
        }
        LitemallGoodsProduct  GoodsProduct=new LitemallGoodsProduct();
        if(storeAddGoodsForm.getSkuInfo().size()>0){
            //判断是否存在
            LitemallGoodsProductExample goodsProductExample=new LitemallGoodsProductExample();
            goodsProductExample.or().andGoodsIdEqualTo(storeAddGoodsForm.getCommodityId());
            List<LitemallGoodsProduct> litemallGoodsProduct = litemallGoodsProductMapper.selectByExample(goodsProductExample);
            for (int i = 0; i < litemallGoodsProduct.size(); i++) {
                boolean isTrue=true;
                List<LitemallGoodsProductSpecification> productSpecifications=
                        JSONArray.parseArray(litemallGoodsProduct.get(i).getSpecifications(),LitemallGoodsProductSpecification.class);
                for (int k = 0; k < skuFormatDtos.size(); k++) {
                    if(!productSpecifications.contains(skuFormatDtos.get(k))){
                        isTrue=false;
                        break;
                    }
                }
                if(isTrue){
                    GoodsProduct=litemallGoodsProduct.get(i);
                }
            }
            if(ObjectUtil.isNull(GoodsProduct)||GoodsProduct.getId()==null){
                return RespUtil.fail(2000,"商品规格不存在");
            }
        }



        String[] rfids=storeAddGoodsForm.getRfidCode().split(",");
        List<String> rfidList =new ArrayList<>();
        Collections.addAll(rfidList,rfids);
        AgedmallStore store=agedmallStoreMapper.selectByPrimaryKey(agedmallScanGuns.getStoreId());
        List<AgedmallRfidGoodsProduct> rfidGoodsProducts=new ArrayList<>();
        AgedmallRfidGoodsProductExample goodsProductExample=new AgedmallRfidGoodsProductExample();
        goodsProductExample.or().andRfidIn(rfidList).andDeletedEqualTo(false);
        List<AgedmallRfidGoodsProduct> isExistRfidList=agedmallRfidGoodsProductMapper.selectByExample(goodsProductExample);
        List<String> ExistRfids=new ArrayList<>();
        isExistRfidList.forEach( existRfid ->ExistRfids.add(existRfid.getRfid()));
        //去除重复的
        rfidList.removeAll(ExistRfids);
        for (int i = 0; i < rfidList.size(); i++) {
            AgedmallRfidGoodsProduct agedmallRfidGoodsProduct=new AgedmallRfidGoodsProduct();
            agedmallRfidGoodsProduct.setRfid(rfidList.get(i));
            agedmallRfidGoodsProduct.setStoreId(agedmallScanGuns.getStoreId());
            agedmallRfidGoodsProduct.setBusiId(store.getBusiId());
            agedmallRfidGoodsProduct.setGoodsId(storeAddGoodsForm.getCommodityId().longValue());
            agedmallRfidGoodsProduct.setSkuName(storeAddGoodsForm.getSkuName());
            agedmallRfidGoodsProduct.setGoodsProductId(ObjectUtil.isNull(GoodsProduct)||GoodsProduct.getId()==null?null:GoodsProduct.getId().longValue());
            agedmallRfidGoodsProduct.setStat(0);
            agedmallRfidGoodsProduct.setOnlineTime(LocalDateTime.now());
            agedmallRfidGoodsProduct.setAddTime(LocalDateTime.now());
            rfidGoodsProducts.add(agedmallRfidGoodsProduct);
            //新增agedmall_lg_rfid_goods_cur_stat
            agedmallLgRfidStateService.addLgRfidGoods(agedmallScanGuns.getStoreId(),rfidList.get(i),2);
        }
        agedmallLocksMapper.insertRfidGoodsProductList(rfidGoodsProducts);
        return RespUtil.success();

    }


    public BaseResult orderOver(Integer misssionId){
//        logisticBusiBaseServiceImpl.deliveryOverEvent(misssionId);
        return RespUtil.success();
    }

  public BaseResult createMission(String orderCode){
      logisticBusiBaseServiceImpl.userCreateOrderEvent(orderCode,null, LogisticsMissionTypeEnum.ALLOT.getCode());
        return RespUtil.success();
    }

    public BaseResult DirectExchangeProducer(List<Integer> missionid){
        ToLitemallBean toLitemallBean = new ToLitemallBean();
        toLitemallBean.setType(ReceiveOrderResultTypeEum.SENDNOTICE.getCode());
        toLitemallBean.setMissionId(missionid);
        directExchangeProducer.send(JSONUtil.toJsonStr(toLitemallBean), DirectExchangeRabbitMQConfig.TO_LITEMALL_NOTICE);
        return RespUtil.success();
    }


}
